package com.hzqy.service.hotel;

import com.hzqy.commons.utils.RedisUtils;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.persistence.dao.hotel.HotelDao;
import com.hzqy.persistence.dao.hqjc.HqjcDao;
import com.hzqy.service.commons.OrgModelFilterService;
import com.hzqy.service.hqjc.HqjcServiceBean;
import com.hzqy.service.itf.YxtItfServiceBean;
import com.hzqy.web.filter.OrgModelFilter;
import com.hzqy.web.login.SessionKey;
import com.hzqy.web.vo.*;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
public class HotelServiceBean extends OrgModelFilterService{
	protected final Logger LOG = LoggerFactory.getLogger(getClass());

	@Resource
	private HqjcServiceBean hqjcService;
	@Resource
	private HqjcDao hqjcDao;
	@Resource
	private YxtItfServiceBean yxtItfService;
	@Resource
	private HotelDao hotelDao;
	
	/**
	 * 账号如果未注册,则进入这个账号 区分高/标清、 百视通/广电
	 */
	private static final String DEFAULT_NO_ACCOUNT_ZTE_BST_HD = "hzkd_default_account_bst_hd";
	private static final String DEFAULT_NO_ACCOUNT_ZTE_GD_HD = "hzkd_default_account_zte_gd_hd";
	private static final String DEFAULT_NO_ACCOUNT_ZTE_GD_SD = "hzkd_default_account_zte_gd_sd";
	private static final String DEFAULT_NO_ACCOUNT_HW_GD_HD = "hzkd_default_account_hd";
	private static final String DEFAULT_NO_ACCOUNT_HW_GD_SD = "hzkd_default_account_sd";
	
	
	@Override
	public void handleEvent(int Event, Map<String, Object> param) {
		HttpServletRequest request = ((HttpServletRequest)param.get("request"));
		HttpServletResponse response = ((HttpServletResponse)param.get("response"));
		FilterChain chain = ((FilterChain)param.get("chain"));
		OrgModelFilter filter = ((OrgModelFilter)param.get("filter"));
		HttpSession session = request.getSession();
		
		EpgInfoVo epgInfoVo = (EpgInfoVo) session.getAttribute(SessionKey.SESSION_EPGINFO_VO);
		String serverid = epgInfoVo.getOss_user_id();
		Object areaid =session.getAttribute(SessionKey.SESSION_AREA);
		try {
			switch (Event) {
			case SESSION_PMS_ORG_IS_EMPTY:
				
				//判断 广电酒店 和 百视通酒店(以后需要改造)
				if(epgInfoVo.getPartner().toLowerCase().indexOf("bst") >= 0){
					session.setAttribute(SessionKey.SESSION_GROUP_OWNER, 1 + "");
				}else{
					session.setAttribute(SessionKey.SESSION_GROUP_OWNER, 2 + "");
				}
				break;
			case PMS_ORG_OF_SERVERID_NOT_FOUND:
				break;
			case PMS_ORG_OF_SERVERID_FOUND:
				break;
			case MODEL_NOT_FOUND:
				break;
			case USER_PMS_ORG_MODEL_FOUND:
				String pageUrl = epgInfoVo.getPage_url();
				//pageUrl = pageUrl.substring(0, pageUrl.lastIndexOf("/"));
				
				/* 跨分组调用 页面维护由广电完成 酒店分组不做维护 */
				epgInfoVo.setPage_url(pageUrl
						// 2.0酒店高清 -> 酒店行业应用高清
						.replace("ZJTELECOMHotelHD", "gdhdindustry")
						// 2.0酒店标清 -> 酒店行业应用标清
						.replace("ZJTELECOMHotel", "gdsdindustry")
						// 2.0+酒店高清44 -> 34高清
						.replace("frame1044", "frame1034")
						// 2.0+酒店标清45 -> 32标清
						.replace("frame1045", "frame1032"));
				
				PmsOrgVo orgVo = (PmsOrgVo) session.getAttribute(SessionKey.SESSION_USER_FOR_ORG_INFO);
				int f_cc_id = orgVo.getF_cc_id();
				CmContentVo contentVo = new CmContentVo();
				contentVo.setF_cc_name(serverid);
				contentVo.setF_cc_id(f_cc_id);
				contentVo.setF_cc_cprid("1");
				CmContentVo content = hqjcDao.selectContent(contentVo);
				session.setAttribute("contentVo", content);
				
				//查询账户绑定下的商户
				String merchantOrgs = hotelDao.selectOrgsByUserAccount(serverid);
				session.setAttribute("merchantOrgs", merchantOrgs);
				break;
			case USER_PMS_ORG_MODEL_NOT_FOUND:
				//用户没有模版，使用默认账号登录
				String default_account = null;
				//1.标清 2.高清
				String resolution = String.valueOf(session.getAttribute(SessionKey.SESSION_EPG_RESOLUTION));
				
				//4.中兴 否则华为
				if("ZTE".equals(session.getAttribute(SessionKey.SESSION_PARTNER_ID))) {
					//1.百视通 2.广电
					if("1".equals(session.getAttribute(SessionKey.SESSION_GROUP_OWNER))) {
						default_account = DEFAULT_NO_ACCOUNT_ZTE_BST_HD;
					} else {
						if("2".equals(resolution)){
							default_account = DEFAULT_NO_ACCOUNT_ZTE_GD_HD;
						}else{
							default_account = DEFAULT_NO_ACCOUNT_ZTE_GD_SD;
						}
					}
				} else {
					if("2".equals(resolution)){
						default_account = DEFAULT_NO_ACCOUNT_HW_GD_HD;
					}else{
						default_account = DEFAULT_NO_ACCOUNT_HW_GD_SD;
					}
				}
				
				if(areaid!=null){
					PmsOrgVo org_area = yxtItfService.selectContentOrgList(default_account+"_"+areaid, getCatalogidOfServerid()); //查地市默认账号对应的组织
					if(org_area!=null){
						default_account = default_account+"_"+areaid;//默认账号=地市的默认账号
					}
				}
				
				//判断当前账号与默认登录帐号是否相同，相同表示默认账号也无法登录，进入错误页面，避免陷入重定向死循环。
				if(!serverid.equals(default_account)){
					LOG.debug("使用默认账号" + default_account + "登录");
					//账号设置为默认
					epgInfoVo.setOss_user_id(default_account);
					session.removeAttribute(SessionKey.SESSION_USER_FOR_ORG_INFO);
					filter.doFilter(request, response, chain);
				}else{
					response.sendRedirect(request.getContextPath()+"/commons/error.jsp"); //重定向到错误页面
				}
				break;
			default:
				break;
			}
		} catch (Exception e) {
			LOG.error("", e);
		}

/*		Enumeration<String> enums = session.getAttributeNames();
		while(enums.hasMoreElements()){
			String s = enums.nextElement();
			System.out.println(s + " = " + session.getAttribute(s));
		}*/
		
	}

	@Override
	public int getCatalogidOfServerid() {
		return 15;
	}
	
	public List<StatOutlineOrderDataVo> selectOrderDate(StatOutlineOrderDataVo statOutlineOrderDataVo) {
		List<StatOutlineOrderDataVo> list = hotelDao.selectOrderDate(statOutlineOrderDataVo);
		return list;
	}
	
	public int selectHotelBigDataAvg(StatDataBigDataVo statDataBigDataVo) {
		Calendar ca = Calendar.getInstance();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ca.add(Calendar.DATE, -1); //日期减1 
		Date lastDay = ca.getTime(); //结果
		String f_sdbd_dates = "";
		for(int i = 0;i<7;i++){
			String str = sdf.format(lastDay);
			str = "'" +str+"'";
			f_sdbd_dates += str;
			ca.add(Calendar.DATE, -1); //日期减1 
			lastDay = ca.getTime(); //结果
			if(i!=6){
				f_sdbd_dates += ",";
			}
		}
		statDataBigDataVo.setF_sdbd_dates(f_sdbd_dates);
		int result = hotelDao.selectHotelBigDataAvg(statDataBigDataVo);
		return result;
	}
	
	public int selectHotelBigDataMonthSum(StatDataBigDataVo statDataBigDataVo) {
		Date date = new Date();
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		String f_sdbd_date = sdf.format(date);
		statDataBigDataVo.setF_sdbd_date(f_sdbd_date);
		int result = hotelDao.selectHotelBigDataMonthSum(statDataBigDataVo);
		return result;
	}
	
	public List<StatDataBigDataVo> selectHotelBigDataArea(StatDataBigDataVo statDataBigDataVo,int timeType) {
		List<StatDataBigDataVo> list = null;
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
		ca.setTime(new Date()); //设置时间为当前时间 
		ca.add(Calendar.DATE, -1); //日期减1 
		Date lastDay = ca.getTime(); //结果
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(timeType==1){
			String f_sdbd_date = sdf.format(lastDay);
			statDataBigDataVo.setF_sdbd_date(f_sdbd_date);
			list = hotelDao.selectHotelBigDataArea(statDataBigDataVo);
		}else if(timeType==2){//七日
			String f_sdbd_dates = "";
			for(int i = 0;i<7;i++){
				String str = sdf.format(lastDay);
				str = "'" +str+"'";
				f_sdbd_dates += str;
				ca.add(Calendar.DATE, -1); //日期减1 
				lastDay = ca.getTime(); //结果
				if(i!=6){
					f_sdbd_dates += ",";
				}
			}
			statDataBigDataVo.setF_sdbd_dates(f_sdbd_dates);
			list = hotelDao.selectHotelBigDataAreaSeven(statDataBigDataVo);
		}
		return list;
	}
	
	public List<StatDataBigDataVo> selectHotelBigDataActivity(StatDataActivityIndustryVo statDataActivityIndustryVo) {
		List<StatDataBigDataVo> list = new ArrayList<StatDataBigDataVo>();
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
		ca.setTime(new Date()); //设置时间为当前时间 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		if(statDataActivityIndustryVo.getF_sdaia_type()==2){//各地市 
			ca.add(Calendar.DATE, -7); //日期减6 上一周当前时间
			ca.set(Calendar.DAY_OF_WEEK,Calendar.MONDAY);
			Date startDate = ca.getTime(); //结果
			String startDay = sdf.format(startDate);
			ca.add(Calendar.DATE,+6);
			Date endDate = ca.getTime(); //结果
			String endDay = sdf.format(endDate);
			String f_sdaia_date = startDay+"~"+endDay;
			statDataActivityIndustryVo.setF_sdaia_date(f_sdaia_date);
			
			StatDataBigDataVo statDataBigDataVo = new StatDataBigDataVo();
			statDataBigDataVo.setF_sdbd_type(16);
			statDataBigDataVo.setF_sdbd_date(f_sdaia_date);
			list = hotelDao.selectHotelBigDataActivityArea(statDataBigDataVo);
		}else if(statDataActivityIndustryVo.getF_sdaia_type()==1){//七日详情
			ca.add(Calendar.DATE, -1); //日期减1 
			Date lastDay = ca.getTime(); //结果
			String f_sdbd_dates = "";
			for(int i = 0;i<7;i++){
				String str = sdf.format(lastDay);
				str = "'" +str+"'";
				f_sdbd_dates += str;
				ca.add(Calendar.DATE, -1); //日期减1 
				lastDay = ca.getTime(); //结果
				if(i!=6){
					f_sdbd_dates += ",";
				}
			}
			
			StatDataBigDataVo statDataBigDataVo = new StatDataBigDataVo();
			statDataBigDataVo.setF_sdbd_type(15);
			statDataBigDataVo.setF_sdbd_dates(f_sdbd_dates);
			list = hotelDao.selectHotelBigDataActivityProvince(statDataBigDataVo);
		}
		return list;
	}
	
	public List<StatDataBigDataVo> selectHotelBigDataViewing(StatDataBigDataVo statDataBigDataVo) {
		List<StatDataBigDataVo> list = null;
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
		ca.setTime(new Date()); //设置时间为当前时间 
		ca.add(Calendar.DATE, -1); //日期减1 
		Date lastDay = ca.getTime(); //结果
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		
		String f_sdbd_dates = "";
		for(int i = 0;i<7;i++){
			String str = sdf.format(lastDay);
			str = "'" +str+"'";
			f_sdbd_dates += str;
			ca.add(Calendar.DATE, -1); //日期减1 
			lastDay = ca.getTime(); //结果
			if(i!=6){
				f_sdbd_dates += ",";
			}
		}
		statDataBigDataVo.setF_sdbd_dates(f_sdbd_dates);
		list = hotelDao.selectHotelBigDataViewing(statDataBigDataVo);
		return list;
	}
	
	public List<StatDataTotalTopRankingVo> selectHotelBigDataTop8OpenTV(StatDataTotalTopRankingVo statDataTotalTopRankingVo) {
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
		ca.setTime(new Date()); //设置时间为当前时间 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ca.add(Calendar.DATE, -1); //日期减1 
		Date lastDay = ca.getTime(); //结果
		String f_sdttr_date = "";
		for(int i = 0;i<7;i++){
			String str = sdf.format(lastDay);
			str = "'" +str+"'";
			f_sdttr_date += str;
			ca.add(Calendar.DATE, -1); //日期减1 
			lastDay = ca.getTime(); //结果
			if(i!=6){
				f_sdttr_date += ",";
			}
		}
		statDataTotalTopRankingVo.setF_sdttr_date(f_sdttr_date);
		return hotelDao.selectHotelBigDataTop8OpenTV(statDataTotalTopRankingVo);
	}
	
	public List<StatDataTotalTopRankingVo> selectHotelBigDataTop8UseTV(StatDataTotalTopRankingVo statDataTotalTopRankingVo) {
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
		ca.setTime(new Date()); //设置时间为当前时间 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ca.add(Calendar.DATE, -1); //日期减1 
		Date lastDay = ca.getTime(); //结果
		String f_sdttr_date = sdf.format(lastDay);
		statDataTotalTopRankingVo.setF_sdttr_date(f_sdttr_date);
		return hotelDao.selectHotelBigDataTop8UseTV(statDataTotalTopRankingVo);
	}
	
	public List<StatDataUserIncreaseAreaVo> selectHotelBigDataUserIncrease(StatDataUserIncreaseAreaVo statDataUserIncreaseAreaVo) {
		List<StatDataUserIncreaseAreaVo> list = new ArrayList<StatDataUserIncreaseAreaVo>();
		Calendar ca = Calendar.getInstance();//得到一个Calendar的实例 
		ca.setTime(new Date()); //设置时间为当前时间 
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		ca.add(Calendar.DATE, -1); //日期减1 
		Date lastDay = ca.getTime(); //结果
		String f_sdbd_dates = "";
		for(int i = 0;i<7;i++){
			String str = sdf.format(lastDay);
			str = "'" +str+"'";
			f_sdbd_dates += str;
			ca.add(Calendar.DATE, -1); //日期减1 
			lastDay = ca.getTime(); //结果
			if(i!=6){
				f_sdbd_dates += ",";
			}
		}
		statDataUserIncreaseAreaVo.setF_sduia_dates(f_sdbd_dates);
		list = hotelDao.selectHotelBigDataUserIncrease(statDataUserIncreaseAreaVo);
		return list;
	}

	public List<StatDataBigDataVo> selectHotelBigDataList(StatDataBigDataVo statDataBigDataVo) {
		return hotelDao.selectHotelBigDataArea(statDataBigDataVo);
	}

	public List<CmAdvertiseVo> selectHotelAdvertise(HttpSession session,CmAdvertiseVo cmAdvertiseVo) {
		String serverId = String.valueOf(session.getAttribute(SessionKey.SESSION_SERVERID));
		List<CmAdvertiseVo> list_chushi = hotelDao.selectHotelAdvertise(cmAdvertiseVo);
		String dsf_ggxf_model = SystemConfigUtils.getSysConfig(SessionKey.SESSION_SYSTEM_CONFIG.dsf_ggxf_model.getKey());
		List<CmAdvertiseVo> list = new ArrayList<CmAdvertiseVo>(list_chushi);//浅拷贝出来 不对源list进行操作
		if(!list.isEmpty()){
			Iterator<CmAdvertiseVo> iterator = list.iterator();
			while (iterator.hasNext()) {
				CmAdvertiseVo vo = iterator.next();
				String string = String.valueOf(session.getAttribute(vo.getF_ca_position()+"_"+serverId));
				if(vo.getF_ca_position()==1){//开机的广告
					if (dsf_ggxf_model.equals("2")) {
						PmsOrgVo pmsOrgVo = (PmsOrgVo) session.getAttribute(SessionKey.SESSION_USER_FOR_ORG_INFO);
						int f_po_id = pmsOrgVo.getF_po_id();
						int f_ca_contentid_hd = vo.getF_ca_contentid_hd();
						List<CmContentOrgVo> cmContentOrgVos = hotelDao.selectOrgBind(f_ca_contentid_hd);
						if (f_po_id != cmContentOrgVos.get(0).getF_cco_orgId()) {
							iterator.remove();
							continue;
						}
					}
					if(StringUtils.isNotEmpty(string)&&!"null".equals(string)){
						//if(vo.getF_ca_id()==Integer.parseInt(string)){//说明看过了
							iterator.remove();
							continue;
						//}
					}
				}
				if(vo.getF_ca_position()==2){//屏保的广告
					if (dsf_ggxf_model.equals("2")) {
						PmsOrgVo pmsOrgVo = (PmsOrgVo) session.getAttribute(SessionKey.SESSION_USER_FOR_ORG_INFO);
						int f_po_id = pmsOrgVo.getF_po_id();
						int f_ca_contentid_hd = vo.getF_ca_contentid_hd();
						List<CmContentOrgVo> cmContentOrgVos = hotelDao.selectOrgBind(f_ca_contentid_hd);
						if (f_po_id != cmContentOrgVos.get(0).getF_cco_orgId()) {
							iterator.remove();
							continue;
						}
					}
				}
				if(vo.getF_ca_type()==2){//按次数
					String nowUserCount= RedisUtils.getString("ADVERTISE_DATA","hotel_gg_userCount_"+vo.getF_ca_id()+"_"+vo.getF_cas_id()+"_"+serverId);
					int userNowCount = nowUserCount==null?0:Integer.parseInt(nowUserCount);
					vo.setUserNowCount(userNowCount);//把用户观看次数放入结果 返回到前端

					String nowCount= RedisUtils.getString("ADVERTISE_DATA","hotel_gg_nowCount_"+vo.getF_ca_id()+"_"+vo.getF_cas_id());
					int spNowCount = nowCount==null?0:Integer.parseInt(nowCount);
					vo.setSpNowCount(spNowCount);
					int tpNowCount = nowCount==null?0:Integer.parseInt(nowCount);
					vo.setTpNowCount(tpNowCount);
					LOG.debug("查询次数上限类广告信息。广告id： "+vo.getF_ca_id()+",计划id："+vo.getF_cas_id()+",业务账号："+serverId+",用户最多观看次数："+vo.getF_cas_userMaxCount()+",用户已观看次数："+userNowCount+",视频最多观看次数："+vo.getF_cas_spCount()+",视频已观看次数："+spNowCount+",图片最多观看次数："+vo.getF_cas_tpCount()+",图片已观看次数："+tpNowCount+",总观看上限："+vo.getF_cas_maxCount()+",百分率为："+vo.getF_cas_actRate());

					int sumCount = vo.getF_cas_maxCount();
					if(vo.getF_cas_actRate()>0){
						sumCount = vo.getF_cas_maxCount()*vo.getF_cas_actRate()/100;
					}
					LOG.debug("乘以百分率后的总上限次数："+sumCount);
					RedisUtils.setString("ADVERTISE_DATA","hotel_gg_maxSumCount_"+vo.getF_ca_id()+"_"+vo.getF_cas_id(),sumCount+"");
					RedisUtils.setString("ADVERTISE_DATA","hotel_gg_maxUserCount_"+vo.getF_ca_id()+"_"+vo.getF_cas_id(),vo.getF_cas_userMaxCount()+"");
				}

			}
		}
		return list;
	}

	public int updateAdvertiseStrategyStatus(CmAdvertiseVo cmAdvertiseVo) {
		return hotelDao.updateAdvertiseStrategyStatus(cmAdvertiseVo);
	}

	public List<HotelCouponVo> selectCoupon(HotelCouponVo hotelCouponVo) {
		return hotelDao.selectCoupon(hotelCouponVo);
	}

	public List<HotelCouponCodeVo> selectCouponCode(HotelCouponCodeVo hotelCouponCodeVo) {
		List<HotelCouponCodeVo> list = hotelDao.selectCouponCode(hotelCouponCodeVo);

		HotelCouponOrderVo hotelCouponOrderVo = new HotelCouponOrderVo();
		hotelCouponOrderVo.setF_hco_id(hotelCouponCodeVo.getF_hco_id());
		hotelCouponOrderVo.setF_hco_type(3);

		if(!list.isEmpty()){
			hotelDao.updateCouponCodeStatus(list.get(0).getF_hcc_id());
			//入订购记录库
			hotelCouponOrderVo.setF_hco_code(list.get(0).getF_hcc_code());
		}else{
			hotelCouponOrderVo.setF_hco_code("缺少库存，f_hcc_couponid为"+hotelCouponCodeVo.getF_hcc_couponid());
		}
		hotelDao.updateCouponOrder(hotelCouponOrderVo);
		return list;
	}

	public HotelCouponOrderVo insertCouponOrder(HotelCouponOrderVo hotelCouponOrderVo){
		hotelDao.insertCouponOrder(hotelCouponOrderVo);
		return hotelCouponOrderVo;
	}

	public int updateCouponOrder(HotelCouponOrderVo hotelCouponOrderVo){
		return hotelDao.updateCouponOrder(hotelCouponOrderVo);
	}
}
